﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Xml.Serialization;
using System.IO;

public partial class EstimatePromotion : System.Web.UI.Page
{
    double AIS
    {
        get
        {
            if (phone.AisScore<=0)
            {
                return 1;
            }
            else
            {
                double res = phone.AisScore;
                res = res > 1 ? res : 1;
                res = res < 100 ? res : 100;
                return res;
            }
        }
    }

    string UUID
    {
        get
        {
            string uuid = "";
            if (Request.Cookies["UUID"] != null)
            {
                uuid = Request.Cookies["UUID"].Value;
            }
            return uuid;
        }
    }


    UserPhone phone
    {
        get
        {
            if (Session["SESS_USER_PHONE"] == null)
            {
                try
                {
                    Session["SESS_USER_PHONE"] = PhoneLoader.DeserializeFromXML(UUID);
                }
                catch
                {
                    Session["SESS_USER_PHONE"] = new UserPhone(UUID);
                }
            }

            return Session["SESS_USER_PHONE"] as UserPhone;
        }
        set
        {
            Session["SESS_USER_PHONE"] = value;
        }
    }

    double DTAC
    {
        get
        {
            if (phone.DtacScore <=0)
            {
                return 1;
            }
            else
            {
                double res = phone.DtacScore;
                res = res > 1 ? res : 1;
                res = res < 100 ? res : 100;
                return res;
            }
        }
    }

    double TMOVE
    {
        get
        {
            if (phone.TmoveScore <=0)
            {
                return 1;
            }
            else
            {
                double res = phone.TmoveScore;
                res = res > 1 ? res : 1;
                res = res < 100 ? res : 100;
                return res;
            }
        }
    }

    string myProvider
    {
        get
        {
            string res = "ais";
            if (Session["SESS_MYNUM"] == null)
            {
                Session["SESS_MYNUM"] = "ais";
            }
            res = Session["SESS_MYNUM"] as string;
            return res;
        }
        set
        {
            Session["SESS_MYNUM"] = value;
        }
    }

    int ResultNum = 10;

    DataColumn cFromNo = new DataColumn("from_no", typeof(string));
    DataColumn cFromNet = new DataColumn("from_net", typeof(string));
    DataColumn cToNo = new DataColumn("to_no", typeof(string));
    DataColumn cToNet = new DataColumn("to_net", typeof(string));
    DataColumn cDate = new DataColumn("date", typeof(DateTime));
    DataColumn cTime = new DataColumn("time", typeof(double));
    DataColumn cHour = new DataColumn("hour", typeof(int));
    DataColumn cMin = new DataColumn("min", typeof(int));

    Promotions Promotion
    {
        get
        {
            return Session["SESS_PROMOTION"] as Promotions;
        }

        set
        {
            Session["SESS_PROMOTION"] = value;
        }
    }


    DataTable callingLog
    {
        get
        {
            if (Session["SESS_CALL_LOG_TABLE"] == null)
            {
                Session["SESS_CALL_LOG_TABLE"] = new DataTable();
                DataTable tb = Session["SESS_CALL_LOG_TABLE"] as DataTable;
                tb.TableName = "CallingLog";
                tb.Columns.Add(cFromNo);
                tb.Columns.Add(cFromNet);
                tb.Columns.Add(cToNo);
                tb.Columns.Add(cToNet);
                tb.Columns.Add(cDate);
                tb.Columns.Add(cTime);
                tb.Columns.Add(cHour);
                tb.Columns.Add(cMin);
            }

            return Session["SESS_CALL_LOG_TABLE"] as DataTable;
        }
        set
        {
            Session["SESS_CALL_LOG_TABLE"] = value;
        }
    }



    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["SESS_CALL_LOG_TABLE"] == null)
        {
            Response.Redirect("CallLogUpload.aspx");
        }

        if (!IsPostBack)
        {
            txtSms.Text = phone.SmsCount.ToString();
            txtMms.Text = phone.MmsCount.ToString();
            txtNetHour.Text = phone.InternetHour.ToString();
            txtNetMb.Text = phone.InternetMB.ToString();
            txtMbPerHour.Text = phone.InternetMbPerHour.ToString();

            //rdoPaidType.SelectedIndex = phone.PaymentType;
            rdoPrepaid.Checked = phone.PaymentType == 0;
            rdoPostpaid.Checked = phone.PaymentType == 1;
            rdoBothPaid.Checked = phone.PaymentType == 2;

            rdoInternet0.Checked = phone.InternetType == 0;
            rdoInternet1.Checked = phone.InternetType == 1;
            rdoInternet2.Checked = phone.InternetType == 2;
            rdoInternet3.Checked = phone.InternetType == 3;
            rdoInternet4.Checked = phone.InternetType == 4;
            rdoInternet5.Checked = phone.InternetType == 5;
            rdoInternetNone.Checked = phone.InternetType == 6;

            string filename = HttpContext.Current.Server.MapPath(@"App_Data/Promotion.xml");
            if (File.Exists(filename))
            {
                XmlSerializer deserializer = new XmlSerializer(typeof(Promotions));
                TextReader textReader = new StreamReader(filename);
                Promotion = deserializer.Deserialize(textReader) as Promotions;
                textReader.Close();
            }

            AddTopFriends();

            switch (myProvider)
            {
                case "ais": { chkAis.Checked = true; } break;
                case "dtac": { chkDtac.Checked = true; } break;
                case "tmove": { chkTmove.Checked = true; } break;
            }

            double max = Math.Max(AIS, Math.Max(DTAC, TMOVE));

            if (AIS != DTAC && AIS != TMOVE && DTAC != TMOVE)
            {
                if (AIS == max)
                {
                    chkAis.Checked = true;
                }
                if (DTAC == max)
                {
                    chkDtac.Checked = true;
                }
                if (TMOVE == max)
                {
                    chkTmove.Checked = true;
                }
            }

        }

        cFromNo = callingLog.Columns["from_no"];
        cFromNet = callingLog.Columns["from_net"];
        cToNo = callingLog.Columns["to_no"];
        cToNet = callingLog.Columns["to_net"];
        cDate = callingLog.Columns["date"];
        cTime = callingLog.Columns["time"];
        cHour = callingLog.Columns["hour"];
        cMin = callingLog.Columns["min"];


        pnlAis.Controls.Clear();
        pnlDtac.Controls.Clear();
        pnlTmove.Controls.Clear();

        double[] nums = new double[] { AIS, DTAC, TMOVE };

        Array.Sort(nums);

        for (int i = 0; i < 1+ Array.IndexOf(nums,AIS)*2; i ++)
        {
            Image img = new Image();
            img.ImageUrl = "~/images/like.jpg";
            pnlAis.Controls.Add(img);
        }

        for (int i = 0; i < 1 + Array.IndexOf(nums, DTAC)*2; i++)
        {
            Image img = new Image();
            img.ImageUrl = "~/images/like.jpg";
            pnlDtac.Controls.Add(img);
        }

        for (int i = 0; i < 1 + Array.IndexOf(nums, TMOVE)*2; i++)
        {
            Image img = new Image();
            img.ImageUrl = "~/images/like.jpg";
            pnlTmove.Controls.Add(img);
        }

        if (!IsPostBack)
        {
            CalculatePromo();
        }

    }

    void CalculatePromo()
    {
        List<PromoCal> proList = new List<PromoCal>();

        double sms = 0;
        double mms = 0;
        double netHour = 0;
        double netMb = 0;
        double netMbPerHour = 1;

        try { 
            netMbPerHour = phone.InternetMbPerHour;
            //netMbPerHour = netMbPerHour <= 0 ? 1 : netMbPerHour;
        }
        catch { }

        try { sms = phone.SmsCount; }
        catch { }

        try { mms = phone.MmsCount; }
        catch { }

        try {
            if (rdoInternetNone.Checked)
            {
                netMb = 0;
                netHour = 0;
            }
            else if (rdoInternet0.Checked)
            {
                netHour = 20;
                netMb = netHour * netMbPerHour;
            }
            else if (rdoInternet1.Checked)
            {
                netMb = 200;
                netHour = netMb / netMbPerHour;
            }
            else if (rdoInternet2.Checked)
            {
                netMb  = 500;
                netHour = netMb / netMbPerHour;
            }
            else if (rdoInternet3.Checked)
            {
                netMb = 5000;
                netHour = netMb / netMbPerHour;
            }
            else if (rdoInternet4.Checked)
            {
                //netHour = Math.Abs( double.Parse(txtNetHour.Text));
                netHour = phone.InternetHour;
                netMb = netHour * netMbPerHour;
            }
            else if (rdoInternet5.Checked)
            {
                //netMb = Math.Abs( double.Parse(txtNetMb.Text));
                netMb = phone.InternetMB;
                netHour = netMb / netMbPerHour;
            }
        }
        catch { }


        foreach (Provider prov in Promotion.Provider)
        {
            List<string> tops = new List<string>();
            double weight = 1;

            switch (prov.name.ToLower())
            {
                case "ais":
                    {
                        if (!chkAis.Checked) continue;

                        foreach (ListItem itm in chkTopAis.Items)
                        {
                            if (itm.Selected)
                            {
                                tops.Add(itm.Text);
                            }
                        }

                        weight = AIS;
                    }break;
                case "dtac":
                    {
                        if (!chkDtac.Checked) continue;

                        foreach (ListItem itm in chkTopDtac.Items)
                        {
                            if (itm.Selected)
                            {
                                tops.Add(itm.Text);
                            }
                        }

                        weight = DTAC;
                    }break;
                case "tmove":
                case "truemove":
                    {
                        if (!chkTmove.Checked) continue;

                        foreach (ListItem itm in chkTopTmove.Items)
                        {
                            if (itm.Selected)
                            {
                                tops.Add(itm.Text);
                            }
                        }

                        weight = TMOVE;
                    }break;
            }

            foreach (Package pkg in prov.Package)
            {
                if (rdoInternet3.Checked && pkg.InternetPrice > 0)
                {
                    continue;
                }

                if (pkg.PackageType.ToLower() == "core")
                {
                    if (rdoBothPaid.Checked || (rdoPrepaid.Checked && pkg.ProType.ToLower() == "prepaid") || (rdoPostpaid.Checked && pkg.ProType.ToLower() == "postpaid"))
                    {
                        PromoCal promo = new PromoCal(pkg, callingLog, prov.name, sms, mms, netHour,netMb);
                        promo.TopPhone = tops;
                        promo.CallCulate();

                        proList.Add(promo);
                    }
                }
            }
        }

        proList.Sort();

        DataTable dt = new DataTable();
        dt.Columns.Add("Number");
        dt.Columns.Add("Provider");
        dt.Columns.Add("Name");
        dt.Columns.Add("ProType");
        dt.Columns.Add("Description");
        dt.Columns.Add("VoicePrice");
        dt.Columns.Add("SmsPrice");
        dt.Columns.Add("MmsPrice");
        dt.Columns.Add("NetPrice");
        dt.Columns.Add("PriceVat");

        int i = 0;

        foreach (PromoCal pc in proList)
        {
            if (++i > ResultNum)
            {
                break;
            }

            Package pkg = pc.Package;
            //string name = "[" + pc.Provider + " - " + pkg.ProType + "] " + pkg.Name + " price " + pc.FinalPrice;
            //name += " ---- (" + pkg.Description + ")";
            //lstPromo.Items.Add(name);
            DataRow drow = dt.NewRow();

            drow["Number"] = i ;
            drow["Provider"] = pc.Provider;
            drow["Name"] = pkg.Name;
            drow["ProType"] = pkg.ProType;
            drow["Description"] = pkg.Description.Replace(";","<br/>");
            drow["VoicePrice"] = pc.VoicePrice.ToString("#,##0.00");
            drow["SmsPrice"] = pc.SmsPrice.ToString("#,##0.00");
            drow["MmsPrice"] = pc.MmsPrice.ToString("#,##0.00");
            drow["NetPrice"] = pc.InternetPrice.ToString("#,##0.00");
            drow["PriceVat"] = pc.FinalPriceVat.ToString("#,##0.00"); ;// pkg.ProType.ToLower() == "postpaid" ? (pc.FinalPrice * 1.07).ToString("#,##0.00") : pc.FinalPrice.ToString("#,##0.00");

            dt.Rows.Add(drow);
        }

        grdPromotion.DataSource = dt;
        grdPromotion.DataBind();

        if (proList.Count() > 10)
        {
            btnGetAllPromotions.Visible = true;
        }
        else
        {
            btnGetAllPromotions.Visible = false;
        }
    }

    void AddTopFriends()
    {
        if (Session["SESS_TOP_FRIENDS"] != null)
        {
            List<DomainUsage> usage = Session["SESS_TOP_FRIENDS"] as List<DomainUsage>;
            if (usage != null)
            {
                int i = 0;
                foreach (DomainUsage u in usage)
                {
                    if (i > 5)
                    {
                        break;
                    }

                    if (u.Provider == ProviderEnum.AIS)
                    {
                        ListItem l = new ListItem(u.PhoneNum, u.PhoneNum);
                        l.Selected = true;
                        chkTopAis.Items.Add(l);
                        i++;
                    }
                }

                i = 0;
                foreach (DomainUsage u in usage)
                {
                    if (i > 5)
                    {
                        break;
                    }

                    if (u.Provider == ProviderEnum.DTAC)
                    {
                        ListItem l = new ListItem(u.PhoneNum, u.PhoneNum);
                        l.Selected = true;
                        chkTopDtac.Items.Add(l);
                        i++;
                    }
                }

                i = 0;
                foreach (DomainUsage u in usage)
                {
                    if (i > 5)
                    {
                        break;
                    }

                    if (u.Provider == ProviderEnum.TMOVE)
                    {
                        ListItem l = new ListItem(u.PhoneNum, u.PhoneNum);
                        l.Selected = true;
                        chkTopTmove.Items.Add(l);
                        i++;
                    }
                }
            }
        }
    }

    protected void btnEstimate_Click(object sender, EventArgs e)
    {
        try
        {
            try
            {
                phone.SmsCount = Math.Abs(double.Parse(txtSms.Text));
                phone.SmsCount = phone.SmsCount >= 0 ? phone.SmsCount : 0;
                phone.SmsCount = phone.SmsCount < 5000 ? phone.SmsCount : 5000;
                txtSms.Text = phone.SmsCount.ToString();
            }
            catch { txtSms.Text = phone.SmsCount.ToString(); }

            try
            {
                phone.MmsCount = Math.Abs(double.Parse(txtMms.Text));
                phone.MmsCount = phone.MmsCount >= 0 ? phone.MmsCount : 0;
                phone.MmsCount = phone.MmsCount < 5000 ? phone.MmsCount : 5000;
                txtMms.Text = phone.MmsCount.ToString();
            }
            catch { txtMms.Text = phone.MmsCount.ToString(); }

            try
            {
                phone.InternetHour = Math.Abs(double.Parse(txtNetHour.Text));
                phone.InternetHour = phone.InternetHour >= 0 ? phone.InternetHour : 0;
                phone.InternetHour = phone.InternetHour < 750 ? phone.InternetHour : 750;
                txtNetHour.Text = phone.InternetHour.ToString();
            }
            catch { txtNetHour.Text = phone.InternetHour.ToString(); }

            try
            {
                phone.InternetMB = Math.Abs(double.Parse(txtNetMb.Text));
                phone.InternetMB = phone.InternetMB >= 0 ? phone.InternetMB : 0;
                phone.InternetMB = phone.InternetMB < 5000 ? phone.InternetMB : 5000;
                txtNetMb.Text = phone.InternetMB.ToString();
            }
            catch { txtNetMb.Text = phone.InternetMB.ToString(); }

            try
            {
                phone.InternetMbPerHour = Math.Abs(double.Parse(txtMbPerHour.Text));
                phone.InternetMbPerHour = phone.InternetMbPerHour <= 0 ? 1 : phone.InternetMbPerHour;
                phone.InternetMbPerHour = phone.InternetMbPerHour >= 0 ? phone.InternetMbPerHour : 0;
                phone.InternetMbPerHour = phone.InternetMbPerHour < 100 ? phone.InternetMbPerHour : 100;
                txtMbPerHour.Text = phone.InternetMbPerHour.ToString();
            }
            catch { txtMbPerHour.Text = phone.InternetMbPerHour.ToString(); }

            try
            {
                phone.PaymentType = 2;
                if (rdoPrepaid.Checked) { phone.PaymentType = 0; }
                else
                    if (rdoPostpaid.Checked) { phone.PaymentType = 1; }
            }
            catch { }

            try
            {
                int sel = 0;
                if (rdoInternet0.Checked)
                {
                    sel = 0;
                }
                else if (rdoInternet1.Checked)
                {
                    sel = 1;
                }
                else if (rdoInternet2.Checked)
                {
                    sel = 2;
                }
                else if (rdoInternet3.Checked)
                {
                    sel = 3;
                }
                else if (rdoInternet4.Checked)
                {
                    sel = 4;
                }
                else if (rdoInternet5.Checked)
                {
                    sel = 5;
                }
                else if (rdoInternetNone.Checked)
                {
                    sel = 6;
                }

                phone.InternetType = sel;
            }
            catch
            {
            }

            PhoneLoader.SerializeToXML(phone);
            CalculatePromo();
        }
        catch
        {
        }
    }
    protected void btnGetAllPromotions_Click(object sender, EventArgs e)
    {
        try
        {
            ResultNum = int.MaxValue;
            CalculatePromo();
            btnGetAllPromotions.Visible = false;
        }
        catch
        {
        }
    }
}